<?php

namespace App\Admin\Repositories;

use App\Models\Shop as Model;
use Dcat\Admin\Repositories\EloquentRepository;

class Shop extends EloquentRepository
{
    /**
     * Model.
     *
     * @var string
     */
    protected $eloquentClass = Model::class;


    public static function initShop() {
        if(!\Dcat\Admin\Admin::user())return false;
        $id = session('shop_id', 0);
        if($id == 0) {
            if(\Dcat\Admin\Admin::user()->isAdministrator()) {
                $shop = Model::where('status', '1')->first();
                session(['shop'=> $shop]);
                session(['shop_id'=> $shop->id]);
                return $shop;
            }else{
                $id = \DB::table('admin_users_shops')->where('admin_user_id', \Dcat\Admin\Admin::user()->id)->value('shop_id');
            }
        }
        $shop = Model::where('id', $id)->first();
        session(['shop'=> $shop]);
        session(['shop_id'=> $id]);
        return $shop;
    }

    public static function getUserShops(){
        if(\Dcat\Admin\Admin::user()->isAdministrator()) {
            return Model::where('status', '1')->get();
        }else{
            $shop_ids = \DB::table('admin_users_shops')
                ->where('user_id', \Dcat\Admin\Admin::user()->id)->pluck('shop_id');
            return Model::whereIn('id', $shop_ids)->where('status', '1')->get();
        }
    }

    public static function changesShop($id){
        $shops = self::getUserShops();
        $shop = $shops->where('id', $id)->first();
        if(!$shop) {
            return ['code'=> 0, 'msg'=> '切换失败: 您没有权限'];
        }
        session(['shop'=> $shop]);
        session(['shop_id'=> $shop->id]);
        return ['code'=> 1, 'msg'=> '切换成功'];

    }
}
